package hu.lacimol.tutorial.todo.action;

import static com.google.common.base.Preconditions.checkNotNull;
import hu.lacimol.tutorial.todo.model.Todo;
import hu.lacimol.tutorial.todo.service.TodoService;

import com.atlassian.jira.web.action.JiraWebActionSupport;

public class TodoAction extends JiraWebActionSupport {

	private static final long serialVersionUID = -2345865120367035004L;

	protected final static String VIEW_PAGE = "ViewTodoAction.jspa";

	protected final TodoService todoService;

	public TodoAction(TodoService todoService) {
		this.todoService = checkNotNull(todoService);
	}

	protected void doKeyValidation() {
		log.debug("Entering doKeyValidation");
		final String id = request.getParameter("key");
		if (id == null || id.isEmpty()) {
			//?key=
			addErrorMessage(getText("todo.form.id.missing"));
		} else {
			try {
				todo = this.todoService.findById(Integer.valueOf(id));
				todo.getDescription();
			} catch (NumberFormatException e) {
				//?key=aaa
				addErrorMessage(getText("todo.form.id.wrong.format"));
			} catch (NullPointerException e) {
				//?key=111
				addErrorMessage(getText("todo.form.not.found"));
			}

		}
	}

	protected void doFieldValidation() {
		final String description = request.getParameter("description");
		if (description == null || description.isEmpty()) {
			addErrorMessage(getText("todo.form.description.missing"));
		}
		int maxLength = 50;
		if (description != null && description.length() > maxLength) {
			addErrorMessage(getText("todo.form.description.too.long"));
		}
	}

	protected Todo todo;
	public Todo getTodo() {
		return todo;
	}

}